package com.ruyuan.payment.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruyuan.payment.server.domain.Course;
import com.ruyuan.payment.server.domain.CourseExample;
import com.ruyuan.payment.server.mapper.CourseMapper;
import com.ruyuan.payment.server.req.CourseAddReq;
import com.ruyuan.payment.server.req.CourseModifyReq;
import com.ruyuan.payment.server.req.CourseQueryReq;
import com.ruyuan.payment.server.resp.CourseQueryResp;
import com.ruyuan.payment.server.resp.PageResp;
import com.ruyuan.payment.server.util.CopyUtil;
import com.ruyuan.payment.server.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CourseService {

    private static final Logger LOG = LoggerFactory.getLogger(CourseService.class);

    @Resource
    private CourseMapper courseMapper;

    @Resource
    private SnowFlake snowFlake;

    public long count() {
        return courseMapper.countByExample(null);
    }

    public void add(CourseAddReq req) {
        Course course = CopyUtil.copy(req, Course.class);
        course.setId(snowFlake.nextId());
        courseMapper.insert(course);
    }

    public void modify(CourseModifyReq req) {
        Course course = CopyUtil.copy(req, Course.class);
        courseMapper.updateByPrimaryKey(course);
    }

    public void delete(Long id) {
        courseMapper.deleteByPrimaryKey(id);
    }

    public PageResp<CourseQueryResp> queryList(CourseQueryReq req) {
        String name = req.getName();
        CourseExample courseExample = new CourseExample();
        CourseExample.Criteria criteria = courseExample.createCriteria();
        if (!ObjectUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        LOG.info("查询页码：{}", req.getPage());
        LOG.info("每页条数：{}", req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Course> courseList = courseMapper.selectByExample(courseExample);

        PageInfo<Course> pageInfo = new PageInfo<>(courseList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        // List<CourseQueryResp> list = new ArrayList<>();
        // for (int i = 0; i < courseList.size(); i++) {
        //     Course course = courseList.get(i);
        //     CourseQueryResp courseQueryResp = new CourseQueryResp();
        //     BeanUtils.copyProperties(course, courseQueryResp);
        //     list.add(courseQueryResp);
        // }
        List<CourseQueryResp> queryRespList = CopyUtil.copyList(courseList, CourseQueryResp.class);

        PageResp<CourseQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(queryRespList);

        return pageResp;
    }
}
